package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.person;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.SocialCircleActivity;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.detail.DynamicDetailFragment;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;

public class PersonDynamicFragment extends BaseMvpFragment<PersonDynamicPresenter> implements DynamicContract.PersonIndexView {

    @BindView(R.id.rv_list)
    RecyclerView rvList;

    private PersonDynamicAdapter mAdapter;

    private int userId;

    private boolean isLoadingMore = false;
    private boolean isEnd = false;
    private int pageNum = 1;
    private int pageSize = 6;

    public static PersonDynamicFragment newInstance(int userId) {
        Bundle bundle = new Bundle();
        bundle.putInt("userId", userId);
        PersonDynamicFragment fragment = new PersonDynamicFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userId = getArguments().getInt("userId");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.widget_list_base;
    }

    @Override
    protected void initView() {

        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isEnd) {
                    return;
                }

                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (linearLayoutManager == null) return;
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {  //还剩2个Item时加载更多
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        mPresenter.fetchList((int) mAdapter.getLastItemId(), 10, userId);
                    }
                }
            }
        });

        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new PersonDynamicAdapter();
        rvList.setAdapter(mAdapter);

        View footerView = View.inflate(getContext(), R.layout.item_common_footer, null);
        mAdapter.setFooterView(footerView);
        mAdapter.setOnItemClickListener((adapter, view, position) ->
                ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                        .withString(SocialCircleActivity.FRAGMENT_KEY, DynamicDetailFragment.CIRCLE_CARD_DETAIL)
                        .withInt("dynamicId", (int) mAdapter.getItemId(position))
                        .navigation());
        mAdapter.setOnContractEventListener(position -> {
            rvList.smoothScrollToPosition(position);
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPresenter.fetchList(0, 10, userId);
    }

    @Override
    public void onGetPersonDynamic(List<DynamicResult> circleHomeResults) {
        if (isLoadingMore) {
            isLoadingMore = false;
            isEnd = circleHomeResults.size() < pageSize;
            mAdapter.addData(circleHomeResults);
        } else {
            mAdapter.setList(circleHomeResults);
        }
    }

    @Override
    public void onGetPersonInfo(UserResult result) {
    }

    void setRefresh() {
        mPresenter.fetchList(0, pageSize, userId);
    }

    @Subscribe
    public void OnDynamicEvent(HomeEvent event) {
        if (event.getEvent() == HomeEvent.DYNAMIC_DELETE) {
            mAdapter.deleteById(event.getDynamicId());
        }
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        if (isLoadingMore) {
            isLoadingMore = false;
        }
    }

}
